package com.hongyuan.sellfitness.ui.home.view_mode;

import android.app.Application;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;
import com.hongyuan.mvvmhabitx.binding.command.BindingCommand;
import com.hongyuan.mvvmhabitx.bus.RxBus;
import com.hongyuan.mvvmhabitx.bus.RxSubscriptions;
import com.hongyuan.mvvmhabitx.bus.event.SingleLiveEvent;
import com.hongyuan.sellfitness.BR;
import com.hongyuan.sellfitness.R;
import com.hongyuan.sellfitness.base.Constants;
import com.hongyuan.sellfitness.base.CustomViewModel;
import com.hongyuan.sellfitness.data.MyRepository;
import com.hongyuan.sellfitness.data.rxbus.ChangeStoreMessage;
import com.hongyuan.sellfitness.my_view.scllor_view.UnitBeanUtils;
import com.hongyuan.sellfitness.ui.home.activity.ReservationActivity;
import com.hongyuan.sellfitness.ui.home.activity.StoreCardActivity;
import com.hongyuan.sellfitness.ui.home.activity.StoreCoachActivity;
import com.hongyuan.sellfitness.ui.home.activity.StoreListActivity;
import com.hongyuan.sellfitness.ui.home.activity.StorePriviteLessonActivity;
import com.hongyuan.sellfitness.ui.home.beans.CoachListBean;
import com.hongyuan.sellfitness.ui.home.beans.GroupClassBean;
import com.hongyuan.sellfitness.ui.home.beans.HomeMyCardsBean;
import com.hongyuan.sellfitness.ui.home.beans.MemberOsBean;
import com.hongyuan.sellfitness.ui.home.beans.QRScanResultBean;
import com.hongyuan.sellfitness.ui.home.beans.SalerBean;
import com.hongyuan.sellfitness.ui.home.beans.ShowQrBean;
import com.hongyuan.sellfitness.ui.home.beans.StoreInfoBean;
import com.hongyuan.sellfitness.ui.home.beans.CheckQrBean;
import com.hongyuan.sellfitness.ui.home.beans.UseQrBean;
import com.hongyuan.sellfitness.ui.main.beans.AuthorityBean;

import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class FragmentHomeViewModel extends CustomViewModel<MyRepository> {

    private Disposable mSubscription;

    //二维码my_card_id
    public String my_card_id = "";
    //当前时间点
    private String is_code = "";
    //需要传递的二维码信息
    public UseQrBean useQrBean;

    //配送方式选择工具类
    public UnitBeanUtils rUtils;
    //会籍卡数据
    public List<HomeMyCardsBean.ListBean> cardList;

    public ObservableField<StoreInfoBean> entity = new ObservableField<>();

    //给RecyclerView添加ObservableList
    public ObservableList<HomeCoachItemViewModel> coachList = new ObservableArrayList<>();

    //给RecyclerView添加ItemBinding
    public ItemBinding<HomeCoachItemViewModel> coachBinding = ItemBinding.of(BR.viewModel, R.layout.item_home_coach);

    //给RecyclerView添加ObservableList
    public ObservableList<HomeGroupItemViewModel> groupList = new ObservableArrayList<>();

    //给RecyclerView添加ItemBinding
    public ItemBinding<HomeGroupItemViewModel> groupBinding = ItemBinding.of(BR.viewModel, R.layout.item_home_group);

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();
    public class UIChangeObservable {
        //显示进出店二维码
        public SingleLiveEvent<UseQrBean> showQrDialog = new SingleLiveEvent<>();
        //关闭二维码弹框
        public SingleLiveEvent<Boolean> closeQrDialog = new SingleLiveEvent<>();
        //销售顾问初始值
        public SingleLiveEvent<List<SalerBean.ListBean>> setSalers = new SingleLiveEvent<>();
        //显示销售顾问滚动弹框
        public SingleLiveEvent<Void> showSaler = new SingleLiveEvent<>();
        //弹框显示会籍卡显示
        public SingleLiveEvent<Void> showCards = new SingleLiveEvent<>();
    }

    public FragmentHomeViewModel(@NonNull Application application, MyRepository repository) {
        super(application, repository);
    }

    //门店列表
    public BindingCommand goStoreList = new BindingCommand(() -> startActivity(StoreListActivity.class));

    //我的会员卡
    public BindingCommand goMyCard = new BindingCommand(() -> {
        Bundle bundle = new Bundle();
        bundle.putString("os_id",String.valueOf(entity.get().getOs_id()));
        startActivity(StoreCardActivity.class,bundle);
    });

    //预约
    public BindingCommand goReservation = new BindingCommand(() -> {
        Bundle bundle = new Bundle();
        bundle.putString("os_id",String.valueOf(entity.get().getOs_id()));
        startActivity(ReservationActivity.class,bundle);
    });

    //门店私教课
    public BindingCommand goStoreLesson = new BindingCommand(() -> {
        Bundle bundle = new Bundle();
        bundle.putString("os_id",String.valueOf(entity.get().getOs_id()));
        startActivity(StorePriviteLessonActivity.class,bundle);
    });

    //展示二维码
    public BindingCommand showQr = new BindingCommand(() -> {
        requestData(Constants.GET_COME_CARD);
    });

    //显示会籍顾问
    public BindingCommand showSaler = new BindingCommand(() -> {
        uc.showSaler.call();
    });

    //去教练列表
    public BindingCommand goCoachList = new BindingCommand(() -> {
        Bundle bundle = new Bundle();
        bundle.putString("os_id",String.valueOf(entity.get().getOs_id()));
        startActivity(StoreCoachActivity.class,bundle);
    });

    @Override
    public void onCreate() {
        super.onCreate();

        mSubscription = RxBus.getDefault().toObservable(ChangeStoreMessage.class)
                .observeOn(AndroidSchedulers.mainThread()) //回调到主线程更新UI
                .subscribe(progressLoadBean -> {
                    coachList.clear();
                    groupList.clear();

                    //更新下数据
                    //请求门店信息
                    clearParams().setParams("os_id",progressLoadBean.getOs_id())
                    .setParams("os_ids",String.valueOf(progressLoadBean.getOs_id()));
                    requestData(Constants.GET_COURSE_SUPER_LIST);
                    requestData(Constants.GET_OFFLINE_STORE_INFO);
                    requestData(Constants.GET_SALER_LIST);

                    requestData(Constants.GET_COACH_LIST);
                });
        //将订阅者加入管理站
        RxSubscriptions.add(mSubscription);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        //取消订阅，防止内存泄漏
        RxSubscriptions.remove(mSubscription);
    }

    @Override
    protected void returnData(int code, Object dataBean) {
        super.returnData(code, dataBean);

        if(code == Constants.GET_MEMEBER_OS){
            List<MemberOsBean.ListBean> list = ((MemberOsBean)dataBean).getList();
            if(list != null && list.size() > 0){

                //更改全局os_id
                userToken.setOs_id(String.valueOf(list.get(0).getOs_id()));

                //请求门店信息
                clearParams().setParams("os_id",String.valueOf(list.get(0).getOs_id()));
                requestData(Constants.GET_OFFLINE_STORE_INFO);

                //请求门店教练
                //clearParams().setParams("os_id",String.valueOf(list.get(0).getOs_id()));
                requestData(Constants.GET_COACH_LIST);

                //请求门店团课
                setParams("os_ids",String.valueOf(list.get(0).getOs_id()));
                requestData(Constants.GET_COURSE_SUPER_LIST);

                //请求门店权限（发现）
                setParams("os_id",String.valueOf(list.get(0).getOs_id()))
                        .setParams("role_code","circle");
                requestData(Constants.VERIFY_ROLE);

                //读取销售顾问
                setParams("os_id",userToken.getOs_id());
                requestData(Constants.GET_SALER_LIST);
            }
        }

        if(code == Constants.VERIFY_ROLE){
            AuthorityBean bean = (AuthorityBean)dataBean;
            //设定死的，权限功能服务端还有问题
            bean.setState(1);
            //设置全局权限管理
            userToken.setFindState(bean.getState());
        }

        if(code == Constants.GET_SALER_LIST){
            List<SalerBean.ListBean> mList = ((SalerBean)dataBean).getList();

            uc.setSalers.setValue(mList);

            rUtils = new UnitBeanUtils<SalerBean.ListBean>() {
                @Override
                public String unit(SalerBean.ListBean o) {
                    return String.valueOf(o.getM_id());
                }

                @Override
                public String unit_cn(SalerBean.ListBean o) {
                    return o.getMi_realname();
                }
            };
        }

        if(code == Constants.GET_OFFLINE_STORE_INFO){
            StoreInfoBean infoBean = (StoreInfoBean)dataBean;

            entity.set(infoBean);
        }

        if(code == Constants.GET_COACH_LIST){
            List<CoachListBean.ListBean> mList = ((CoachListBean)dataBean).getList();
            for (CoachListBean.ListBean bean : mList){
                HomeCoachItemViewModel itemViewModel = new HomeCoachItemViewModel(this,bean);
                coachList.add(itemViewModel);
            }
        }

        if (code == Constants.GET_COME_CARD) {
            cardList = ((HomeMyCardsBean)dataBean).getList();

            uc.showCards.call();
        }

        if(code == Constants.CHECK_COME_OR_OFF_STORE){
            CheckQrBean qrBean = (CheckQrBean)dataBean;
            is_code = String.valueOf(System.currentTimeMillis());
            useQrBean.setIs_code(is_code);
            useQrBean.setIs_in(qrBean.getIs_in());
            clearParams().clearParams().setParams("my_card_id",my_card_id)
                    .setParams("is_type",qrBean.getIs_in().equals("0") ? "1" : "2")
                    .setParams("is_code",is_code);

            requestData(Constants.SHOW_CODE);
        }

        if(code == Constants.SHOW_CODE){
            ShowQrBean qrBean = (ShowQrBean)dataBean;
            useQrBean.setQrImgUrl(qrBean.getImg());
            uc.showQrDialog.setValue(useQrBean);
        }

        if(code == Constants.CHECK_DO_CARD){
            QRScanResultBean bean = (QRScanResultBean)dataBean;

            if(bean.getIs_ok() != 0){
                uc.closeQrDialog.call();
            }
        }

        if(code == Constants.GET_COURSE_SUPER_LIST){
            List<GroupClassBean.ListBean> group = ((GroupClassBean)dataBean).getList();

            if(group != null && group.size() > 0){
                for(GroupClassBean.ListBean bean : group){
                    HomeGroupItemViewModel itemViewModel = new HomeGroupItemViewModel(this,bean);
                    groupList.add(itemViewModel);
                }
            }
        }
    }

    /*
    * 获取销售顾问的电话
    * */
    public String getSalerTel(List<SalerBean.ListBean> mList,String name){
        for(SalerBean.ListBean bean : mList){
            if(name.equals(bean.getMi_realname())){
                return bean.getM_mobile();
            }
        }
        return "";
    }
}
